package tmt.usercenter.web.domain.converter;

import tmt.usercenter.web.domain.enums.AuthorizedGrantType;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by ThreeManTeam on 2017/5/10.
 */

@Converter
public class StringAndEnumListConverter implements AttributeConverter<List<AuthorizedGrantType>, String> {

    @Override
    public String convertToDatabaseColumn(List<AuthorizedGrantType> attribute) {
        if (attribute == null || attribute.size() <= 0)
            return "";
        return attribute.stream().map(Enum::name).reduce((i,o)->i + "|" + o).get();
    }

    @Override
    public List<AuthorizedGrantType> convertToEntityAttribute(String dbData) {
        if (dbData == null || "".equals(dbData.trim()))
            return new ArrayList<>();

        return Arrays.stream(dbData.split("\\|")).filter(x->x.length()> 0)
                .map(x->Enum.valueOf(AuthorizedGrantType.class, x)).collect(Collectors.toList());
    }
}
